<script setup lang="ts">
import { reactive, onMounted } from 'vue';
import { My as AppNutIconMy } from '@nutui/icons-vue-taro';
import { fileNameForUploadFile, uploadImageFile } from '/@/utils/file';
import {
  login,
  showModal,
  showActionSheet,
  showToast,
  showLoading,
  hideLoading,
  reLaunch,
  navigateTo,
  removeStorage,
  chooseImage,
} from '@tarojs/taro';
import { APP_EDITION, APP_ROLE_PLATFORM } from '/@/common/constant';
import {
  LOGIN_APP,
  CHANGE_ROLE_PLATFORM_APP,
  UPDATE_USER_ICON_APP,
} from '/@/api/modules/base/app-sys-user';
import { WX_USER_BIND, WX_USER_UNBIND } from '/@/api/modules/wechat/index';
import { getSysImgUrl } from '/@/utils/index';
import IMG_WHITE_BG from '/@/assets/image/bg/white-bg.png';
import IMG_FILE_1 from '/@/assets/image/icon/file-1.png';
import IMG_OPEN_LOCK from '/@/assets/image/icon/open-lock.png';
import MyStaffManage from './components/my-staff-manage.vue';
import MyLogisticsManage from './components/my-logistics-manage.vue';
const state = reactive<{
  /**
   * 应用版本
   */
  appEdition: keyof typeof APP_EDITION;
  /**
   * 应用环境
   */
  appEnv: string;
  /**
   * taro应用环境
   */
  taroEnv: string;
  userInfo: AppSysUser.Dto;
  organDtos: AppSysOrgan.Dto[];
  sysRoleDto: AppSysRole.Dto;
  currentRolePlatformCode: AppSysUserApi.LoginAppResp['currentRolePlatformCode'];
}>({
  appEdition: (process.env.APP_EDITION as keyof typeof APP_EDITION) || 'default',
  appEnv: process.env.APP_ENV || '',
  taroEnv: process.env.TARO_ENV,
  userInfo: {
    name: '',
    nickName: '',
    icon: '',
  },
  organDtos: [],
  sysRoleDto: {
    rolePlatformLogistics: 2,
    rolePlatformStaff: 2,
  },
  currentRolePlatformCode: 2,
});

/**
 * @function 上传头像
 */
function uploadAvatar() {
  chooseImage({
    count: 1,
    sizeType: ['compressed'],
    success: (res) => {
      const { originalFileObj, path } = res.tempFiles[0];
      const suffix = originalFileObj?.name.substring(originalFileObj?.name.lastIndexOf('.')) || ''; //取文件名后缀
      const fileName = fileNameForUploadFile(suffix);
      const originalFileName = originalFileObj?.name || '';
      uploadImageFile(path, originalFileName, fileName, 'public', (url: string) => {
        UPDATE_USER_ICON_APP({
          icon: url,
        }).then(() => {
          showToast({
            title: '修改头像成功',
            icon: 'success',
          });
          LOGIN_APP().then((res) => {
            state.userInfo = res.sysUserDto;
          });
        });
      });
    },
  });
}

/**
 * @function 选择版本
 */
function selectEdition() {
  if (state.sysRoleDto.rolePlatformLogistics !== 1 || state.sysRoleDto.rolePlatformStaff !== 1)
    return;

  showActionSheet({
    itemList: ['后勤版', '员工版'],
    success: (res) => {
      if (res.tapIndex + 2 === state.currentRolePlatformCode) return;

      CHANGE_ROLE_PLATFORM_APP({ rolePlatformCode: (res.tapIndex + 2) as 2 | 3 }).then(() => {
        reLaunch({
          url: `/pages/index/index`,
        });
      });
    },
  });
}

/**
 * @function 退出登录
 */
function logout() {
  showModal({
    content: '确认退出登录？',
    confirmColor: '#ff514e',
    success: (res) => {
      if (res.confirm) {
        removeStorage({
          key: 'token',
          success() {
            reLaunch({
              url: '/pages/user/login/index?toPage=/pages/index/index',
            });
          },
        });
      }
    },
  });
}

onMounted(() => {
  LOGIN_APP().then((res) => {
    state.userInfo = res.sysUserDto;
    state.sysRoleDto = res.sysRoleDto[0];
    state.organDtos = res.organDtos;
    state.currentRolePlatformCode = res.currentRolePlatformCode;
  });
});
</script>

<template>
  <view class="my app-page--1">
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="my__header">
        <view class="my__header__container">
          <view class="my__header__container--left">
            <nut-avatar class="my__avatar" size="large" shape="round" @click="uploadAvatar">
              <image v-if="state.userInfo.icon" :src="getSysImgUrl(state.userInfo.icon)" />
              <app-nut-icon-my v-else />
            </nut-avatar>
          </view>
          <view class="my__header__container--right">
            <view class="my__name">{{ state.userInfo.name || state.userInfo.nickName }}</view>
            <view
              class="my__name--sub"
              @click="
                showModal({
                  showCancel: false,
                  content: `${state.organDtos
                    .map((item) => {
                      return item.name;
                    })
                    .toString()} - ${state.sysRoleDto.name}`,
                })
              "
            >
              {{
                state.organDtos && state.organDtos.length > 4
                  ? `${state.organDtos
                      .slice(0, 4)
                      .map((item) => {
                        return item.name;
                      })
                      .toString()}...`
                  : state.organDtos
                      .map((item) => {
                        return item.name;
                      })
                      .toString()
              }}
              -
              {{ state.sysRoleDto.name }}
            </view>
          </view>
        </view>
        <image class="my__header__bg" mode="widthFix" :src="IMG_WHITE_BG" />
      </view>
      <view class="my__header__bottom" v-if="['default'].includes(state.appEdition)">
        <my-staff-manage v-if="state.currentRolePlatformCode === 3" />
        <my-logistics-manage v-else />
      </view>
      <view class="my__wrapper">
        <nut-cell-group>
          <nut-cell
            title="当前版本"
            :is-link="
              state.sysRoleDto.rolePlatformLogistics === 1 &&
              state.sysRoleDto.rolePlatformStaff === 1
            "
            :desc="APP_ROLE_PLATFORM[state.currentRolePlatformCode]"
            @click="selectEdition()"
          >
            <template v-slot:icon>
              <image class="my__icon" mode="widthFix" :src="IMG_FILE_1" />
            </template>
          </nut-cell>
          <nut-cell
            v-if="
              ['default', 'jinhua-police-service', 'can-nang-third-hospital'].includes(
                state.appEdition,
              )
            "
            title="修改密码"
            is-link
            @click="
              () => {
                navigateTo({
                  url: '/pages/user/update-password/index',
                });
              }
            "
          >
            <template v-slot:icon>
              <image class="my__icon" mode="widthFix" :src="IMG_OPEN_LOCK" />
            </template>
          </nut-cell>
          <nut-cell
            v-if="state.taroEnv === 'weapp'"
            title="绑定微信"
            @click="
              () => {
                showLoading();
                login({}).then((res1) => {
                  WX_USER_BIND({ code: res1.code })
                    .then((res2) => {
                      hideLoading();
                      showModal({ content: res2.comResp?.msg, showCancel: false });
                    })
                    .catch(() => {
                      hideLoading();
                    });
                });
              }
            "
          />
          <nut-cell
            v-if="state.taroEnv === 'weapp'"
            title="解绑微信"
            @click="
              () => {
                showLoading();
                login({}).then((res1) => {
                  WX_USER_UNBIND({ code: res1.code })
                    .then((res2) => {
                      hideLoading();
                      showModal({ content: res2.comResp?.msg, showCancel: false });
                    })
                    .catch(() => {
                      hideLoading();
                    });
                });
              }
            "
          />
        </nut-cell-group>
      </view>
    </scroll-view>
    <view
      v-if="
        ['default', 'hgy', 'jinhua-police-service', 'can-nang-third-hospital'].includes(
          state.appEdition,
        ) || ['development'].includes(state.appEnv)
      "
      class="my__footer"
    >
      <nut-button type="danger" block @click="logout()">退出登录</nut-button>
    </view>
    <app-tab-bar active="my" />
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
